# 个人中心视图接口
from flask import abort
from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import render_template
from flask import request

from info import constants, db
from info.models import User, Category, News
from info.modules.profile import profile_url
from info.response_code import RET
from info.utils.common import user_logo_data
from info.utils.image_storage import storage


@profile_url.route('/info')
@user_logo_data
def get_user_info():

        user = g.user
        if not user:
            return redirect('/')

        data = {
            "user": user.to_dict() if user else None
        }

        return render_template("news/user.html", data=data)





@profile_url.route('/base_info',methods=['POST',"GET"])
@user_logo_data
def base_info():
    if request.method=="GET":
        user = g.user
        if not user:
            return jsonify(errno=RET.PARAMERR, errmsg='用户未登录')



        data={
            "user":user.to_dict() if user else None
        }

        return render_template("news/user_base_info.html",data=data)

    else:
        nick_name=request.json.get("nick_name")
        signature=request.json.get('signature')
        gender = request.json.get("gender")
        if not all([nick_name,signature,gender]):
            return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
        if gender not in ('MAN','WOMAN'):
            return jsonify(errno=RET.PARAMERR, errmsg='性别错误')

        user=g.user
        user.gender=gender
        user.signature=signature
        user.nick_name=nick_name
        return jsonify(errno=RET.OK, errmsg='Ok')

@profile_url.route('/pic_info',methods=['GET','POST'])
@user_logo_data
def get_user_image():
    """更换图像"""
    user=g.user

    if request.method=='GET':
        data = {'user': user.to_dict()}
        return render_template('news/user_pic_info.html',data=data)
    else:
        try:
            # 接受前端传过来的图片
            avatar = request.files.get('avatar').read()
        except Exception as e :
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
        # 上传用户的图片到七牛云
        try:
            key = storage(avatar)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR,errmsg="上传失败")

        user.avatar_url=key
        return jsonify(errno=RET.OK,errmsg="上传成功",data={'avatar_url':constants.QINIU_DOMIN_PREFIX+key})

@profile_url.route('/pass_info',methods=['GET','POST'])
@user_logo_data
def pass_info():
    """密码修改"""
    user = g.user
    if request.method=="GET":
        return render_template('news/user_pass_info.html',data=user.to_dict())
    else:
        new_password=request.json.get("new_password")
        old_password=request.json.get("old_password")
    if not all([new_password,old_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if not user.check_passward(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="密码错误")
    user.password=new_password
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")


    return jsonify(errno=RET.OK, errmsg="修改成功")

@profile_url.route('/collection',methods=['GET','POST'])
@user_logo_data
def user_collection():
    """w我的收藏"""
    page =request.args.get("p",1)

    try:
        page=int(page)
    except Exception as e:
        current_app.logger.error(e)
        # 如果穿错了就默认为第一页
        page=1

    user=g.user
    collections=[]
    current_page=1
    totle_page=1
    try:
        paginate = user.collection_news.paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        current_page=paginate.page
        totle_page =paginate.pages
        collections=paginate.items
    except Exception as e:
        current_app.logger.error(e)

    # 遍历collectio对象列表
    collections_li = []
    for collection in collections:
        collections_li.append(collection)

    data={
        'current_page':current_page,
        'totle_page':totle_page,
        'collections':collections_li
    }

    return render_template('news/user_collection.html',data=data)

@profile_url.route('/news_release',methods=['GET','POST'])
@user_logo_data
def user_release():
    """新闻发表"""
    if request.method=='GET':
        categories=[]
        try:
            categories=Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        category_li=[]
        for category in categories:
            category_li.append(category)

        category_li.pop(0)
        data={
            'categories':category_li
        }

        return render_template('news/user_news_release.html',data=data)
    else:
        title = request.form.get('title')
        digest = request.form.get('digest')
        source = " 个人发布"
        content = request.form.get('content')
        index_image = request.files.get('index_image')
        categories = request.form.get('category_id')


    if not all([title,digest,content,index_image,categories]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        index_image=index_image.read()

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
       key=storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="图片上传失败")

    news=News()
    news.title=title
    news.digest=digest
    news.content=content
    news.index_image_url=constants.QINIU_DOMIN_PREFIX + key
    news.category_id =categories
    news.user_id=g.user.id
    news.source =source
    news.status=1


    try :
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()

    return jsonify(errno=RET.OK, errmsg="ok")


@profile_url.route('/news_list')
@user_logo_data
def get_user_list():

    user=g.user
    page = request.args.get("p",1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")


    try:
        # paginate=user.news_list.order_by(user.create_time).paginate(page,constants.ADMIN_NEWS_PAGE_MAX_COUNT,False)
        paginate= News.query.filter(News.user_id == user.id).order_by(News.create_time.desc()).paginate(page,constants.ADMIN_NEWS_PAGE_MAX_COUNT,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    if not paginate:
        return jsonify(errno=RET.PARAMERR, errmsg="没有当前页")

    page=paginate.page
    total_page = paginate.pages
    contents=paginate.items

    news_list = []
    for content in contents:

        news_list.append(content)

    data = {
        'news_list':news_list,
        'page':page,
        'total_page':total_page

    }
    return render_template('news/user_news_list.html',data=data)


@profile_url.route('/user_follow')
@user_logo_data
def user_follow():
    """我的关注"""
    page = request.args.get('p',1)
    try:
        page=int(page)
    except Exception as e:
        current_app.logger.error(e)
        page=1

    user = g.user
    focus=''
    total_page=1
    current_page=1

    if not  user:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        paginate = user.followed.paginate(page,constants.USER_FOLLOWED_MAX_COUNT,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    if not paginate:
        return jsonify(errno=RET.DBERR, errmsg="数据不存在")

    paginate_li=[]

    current_page = paginate.page
    total_page = paginate.pages
    focus = paginate.items

    for paginates in focus:
        paginate_li.append(paginates)

    data={
        'current_page':current_page,
        'total_page':total_page,
        'users':paginate_li
    }
    return render_template('news/user_follow.html',data=data)

@profile_url.route('/other_info')
@user_logo_data
def other_info():
    '''其他用户详情页面'''
    user=g.user
    if not  user:
        abort(404)
    user_id=request.args.get('user_id')
    if not user_id:
        abort(404)
    other=''
    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)

    if not other:
        abort(404)

    is_followed = False
    if g.user:
        if other.followers.filter(User.id == user.id).count() > 0:
            is_followed = True

    # 组织数据，并返回
    # user_info： 右上角当前登陆用户
    # other_info: 要展示的其他用户的相关信息
    # is_followed: 标示当前用户是否关注过该用户(有两个入口，故该字段有必要)
    data = {
        "user": user.to_dict(),
        "other_info": other.to_dict(),
        "is_followed": is_followed
    }
    return render_template('news/other.html', data=data)

@profile_url.route('/other_news_list')
def other_news_list():
    # 获取页数
    p = request.args.get("p", 1)
    user_id = request.args.get("user_id")
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not all([p, user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")

    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}
    return jsonify(errno=RET.OK, errmsg="OK", data=data)

